package com.heima.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.mapper.ClueMapper;
import com.heima.crm.mapper.CrUserMapper;
import com.heima.crm.mapper.TbBusinessMapper;
import com.heima.crm.mapper.TransferMapper;
import com.heima.crm.pojos.dtos.TransferDto;
import com.heima.crm.pojos.dtos.TransferPageDto;
import com.heima.crm.pojos.entity.TbBusiness;
import com.heima.crm.pojos.entity.TbClue;
import com.heima.crm.pojos.entity.TbTransfer;
import com.heima.crm.pojos.entity.TbUser;
import com.heima.crm.service.TransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.function.DoubleToIntFunction;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TransferServiceImpl implements TransferService {
    @Autowired
    private TransferMapper transferMapper;
    @Autowired
    private TbBusinessMapper tbBusinessMapper;
    @Autowired
    private CrUserMapper crUserMapper;
    @Autowired
    private ClueMapper clueMapper;

    /**
     * 转派分页查询
     *
     * @param transferPageDto
     * @return
     */
    @Override
    public Result page(TransferPageDto transferPageDto) {
        if (transferPageDto.getPage() <= 0 || transferPageDto.getPage() == null) {
            transferPageDto.setPage(1);
        }
        if (transferPageDto.getPageSize() <= 0 || transferPageDto.getPageSize() == null) {
            transferPageDto.setPageSize(10);
        }
        Page page = new Page(transferPageDto.getPage(), transferPageDto.getPageSize());
        LambdaQueryWrapper<TbTransfer> lqw = new LambdaQueryWrapper<>();
        if (transferPageDto.getMinTime() != null) {
            LocalDateTime minTime = transferPageDto.getMinTime().atStartOfDay();
            lqw.ge(TbTransfer::getCreateTime, minTime);
        }
        if (transferPageDto.getMaxTime() != null) {
            LocalDateTime maxTime = transferPageDto.getMaxTime().atTime(23, 59, 59);
            lqw.le(TbTransfer::getCreateTime, maxTime);
        }
        if (transferPageDto.getTel() != null && transferPageDto.getTel() != "") {
            lqw.like(TbTransfer::getTel, transferPageDto.getTel());
        }
        if (transferPageDto.getUserName() != null && transferPageDto.getUserName() != "") {
            lqw.like(TbTransfer::getUserName, transferPageDto.getUserName());
        }
        lqw.orderByDesc(TbTransfer::getCreateTime);
        page = transferMapper.selectPage(page, lqw);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 详情回显
     *
     * @param id
     * @return
     */
    @Override
    public Result display(Long id) {
        TbTransfer tbTransfer = transferMapper.selectById(id);
        return Result.success(tbTransfer);

    }

    /**
     * 转派处理
     *
     * @param transferDto
     * @return
     */
    @Override
    @Transactional
    public Result handle(TransferDto transferDto) {
        //先查到转派详情
        TbTransfer tbTransfer = transferMapper.selectById(transferDto.getTransferId());
        //线索或者是商机
        Short transferType = transferDto.getTransferType();
        if ("0".equals(transferType)) {
            handleClue(tbTransfer, transferDto);

        } else {
            handleBusy(tbTransfer, transferDto);
        }

        return Result.success();
    }

    private void handleClue(TbTransfer tbTransfer, TransferDto transferDto) {
        //转出
        //查转出人具体线索
        LambdaQueryWrapper<TbClue> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbClue::getOwner, tbTransfer.getUserName());
        List<TbClue> tbClues = clueMapper.selectList(lqw);
        List<TbClue> collect = tbClues.stream().limit(transferDto.getNum()).collect(Collectors.toList());
        for (TbClue tbClue : collect) {
            //更新具体线索
            TbUser tbUser = crUserMapper.selectById(transferDto.getUserId());
            tbClue.setOwner(tbUser.getUserName());
            clueMapper.updateById(tbClue);
        }
        //更新转出人总数
        tbTransfer.setClueNum(tbTransfer.getClueNum() - transferDto.getNum());
        transferMapper.updateById(tbTransfer);
        //转入
        //更新转入人总数
        LambdaQueryWrapper<TbTransfer> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(TbTransfer::getUserId, transferDto.getUserId());
        TbTransfer tbTransfer1 = transferMapper.selectOne(lqw1);

        if (tbTransfer1.getClueNum() + transferDto.getNum() > 100) {
            throw new RuntimeException("保有量达到上限,最多可转{}条线索" + (100 - tbTransfer1.getClueNum()));
        }
        tbTransfer1.setClueNum(tbTransfer1.getClueNum() + transferDto.getNum());
        transferMapper.updateById(tbTransfer1);
    }

    private void handleBusy(TbTransfer tbTransfer, TransferDto transferDto) {
        //转出
        //查转出人具体商机
        LambdaQueryWrapper<TbBusiness> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TbBusiness::getAscriptionId, tbTransfer.getUserId());
        List<TbBusiness> transferBusy = tbBusinessMapper.selectList(lqw);
        List<TbBusiness> collect = transferBusy.stream().limit(transferDto.getNum()).collect(Collectors.toList());
        for (TbBusiness tbBusiness : collect) {
            //更新具体商机
            tbBusiness.setAscriptionId(transferDto.getUserId());
            TbUser tbUser = crUserMapper.selectById(transferDto.getUserId());
            tbBusiness.setAscriptionName(tbUser.getUserName());
            tbBusinessMapper.updateById(tbBusiness);
        }
        //更新转出人总数
        tbTransfer.setBusyNum(tbTransfer.getBusyNum() - transferDto.getNum());
        transferMapper.updateById(tbTransfer);

        //转入
        //更新转入人总数
        LambdaQueryWrapper<TbTransfer> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(TbTransfer::getUserId, transferDto.getUserId());
        TbTransfer tbTransfer1 = transferMapper.selectOne(lqw1);
        if (tbTransfer1.getBusyNum() + transferDto.getNum() > 100) {

            throw new RuntimeException("保有量达到上限,最多可转{}条商机" + (100 - tbTransfer1.getBusyNum()));

        }
        tbTransfer1.setBusyNum(tbTransfer1.getBusyNum() + transferDto.getNum());
        transferMapper.updateById(tbTransfer1);
    }
}
